package edu.del.newsreleasesystem.web.controller;

import edu.del.newsreleasesystem.dto.NewsSearchResult;
import edu.del.newsreleasesystem.entity.News;
import edu.del.newsreleasesystem.es.service.NewsEsIndexService;
import edu.del.newsreleasesystem.service.NewsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
public class NewsController {

    private final NewsService newsService;

    private final NewsEsIndexService newsEsIndexService;

    /**
     * 所有新闻
     */
    @GetMapping("/list")
    public ResponseEntity<List<News>> listNews() {
        List<News> newsList = newsService.list();
        return ResponseEntity.ok(newsList);
    }

    /**
     * 根据id查询新闻
     */
    @GetMapping("/news/{id}")
    public ResponseEntity<News> getNewsDetail(@PathVariable Integer id) {
        News news = newsService.getNewsById(id);
        return ResponseEntity.ok(news);
    }

    @GetMapping("/search")
    public ResponseEntity<List<NewsSearchResult>> search(@RequestParam String keyword) {
        List<NewsSearchResult> results = newsEsIndexService.searchNews(keyword);
        return ResponseEntity.ok(results);
    }

    @PostMapping("/publish")
    public ResponseEntity<Void> publishNews(@RequestBody News news) {
        log.info("收到新闻发布请求：{}", news);
        boolean success = newsService.publishNews(news);
        return success ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }

    /**
     * 删除新闻
     */
    @DeleteMapping("/news/{id}")
    public ResponseEntity<Void> deleteNews(@PathVariable Integer id) {
        boolean success = newsService.deleteNews(id);
        return success ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }

    /**
     * 更新新闻
     */
    @PutMapping("/news/{id}")
    public ResponseEntity<Void> updateNews(@PathVariable Integer id, @RequestBody News news) {
        news.setId(id);
        boolean success = newsService.updateNews(news);
        return success ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }
}
